/**
 * 维护“客户自动转交规则”
 */
import { getLogger, Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

const logger = getLogger('services/features/auto-transfer')

interface RespTransferRule {
  Id: number
  Enable: boolean
  LabelIds: string[]
  LabelNames: string[]
  UserIds: string[]
  UserNames: string[]
  WxIds: string[]
}
export interface AutoTransferRule {
  id: number
  enable: boolean
  tags: { id: string; name: string }[]
  accounts: { id: string; name: string }[]
  wxids: string[]
}
function formatTransferRule(raw: RespTransferRule): AutoTransferRule {
  return {
    id: raw.Id,
    enable: raw.Enable,
    tags: raw.LabelIds.map((id, index) => ({ id, name: raw.LabelNames[index] ?? `id:${id}` })),
    accounts: raw.UserIds.map((id, index) => ({ id, name: raw.UserNames[index] ?? `id:${id}` })),
    wxids: raw.WxIds,
  }
}

export class AutoTransfer extends Service<Services> {
  /**
   * 获取转交规则列表
   */
  async getRules() {
    const resp = await API<RespTransferRule[]>('/AutoTransfer/AutoTransferList')
    if (resp.success) {
      return resp.data.map(formatTransferRule).sort((a, b) => a.id - b.id) // 按照 id 倒序排序
    } else {
      logger.warn('获取自动转接规则列表失败', resp.error)
      return []
    }
  }

  /**
   * 新增或修改转交规则
   */
  async addOrUpdateRule(rule: Omit<AutoTransferRule, 'id'> & { id?: number }) {
    const data = {
      ...(rule.id !== undefined ? { Id: rule.id } : {}),
      Enable: rule.enable,
      LabelIds: rule.tags.map(v => v.id),
      LabelNames: rule.tags.map(v => v.name),
      UserIds: rule.accounts.map(v => v.id),
      UserNames: rule.accounts.map(v => v.name),
      Wxids: rule.wxids,
    }
    const resp = await API('/AutoTransfer/AddOrUpdateAutoTransfer', { data })
    return resp.success ? true : resp.error
  }

  /**
   * 启用或禁用一条规则
   */
  async enableRule(id: number, enable: boolean) {
    const resp = await API('/AutoTransfer/EnableAutoTransfer', { data: { Id: id, Enable: enable } })
    return resp.success ? true : resp.error
  }

  /**
   * 删除自动转交规则
   */
  async removeRule(id: number) {
    const resp = await API('/AutoTransfer/RemoveAutoTransfer', { data: { Id: id } })
    return resp.success ? true : resp.error
  }
}
